package com.linked.scheduledtasks.config;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;


@Configuration
public class OkHttpConfiguration {

    @Value("${okHttp.connect-timeout}")
    private Integer connectTimeout;

    @Value("${okHttp.read-timeout}")
    private Integer readTimeout;

    @Value("${okHttp.write-timeout}")
    private Integer writeTimeout;

    @Value("${okHttp.max-idle-connections}")
    private Integer maxIdleConnections;

    @Value("${okHttp.keep-alive-duration}")
    private Long keepAliveDuration;

    @Value("${okHttp.proxy.address:}")
    private String proxyAddress;

    @Value("${okHttp.proxy.port:0}")
    private Integer proxyPort;

    
    @Bean
    public OkHttpClient okHttpClient() {

        if (!StringUtils.isEmpty(proxyAddress) && 0 < proxyPort) {
            return new OkHttpClient.Builder()
                    // 是否开启缓存
                    .retryOnConnectionFailure(false)
                    .connectionPool(pool())
                    .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                    .readTimeout(readTimeout, TimeUnit.SECONDS)
                    .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                    // 设置代理
                    .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))
                    .build();
        } else {
            return new OkHttpClient.Builder()
                    // 是否开启缓存
                    .retryOnConnectionFailure(false)
                    .connectionPool(pool())
                    .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                    .readTimeout(readTimeout, TimeUnit.SECONDS)
                    .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                    .build();
        }
    }

    @Bean
    public ConnectionPool pool() {
        return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
    }
}
